<template>
	<div>
		<el-form ref="form" :model="form" label-width="80px">
			<el-form-item label="标题">
				<el-input v-model="form.title"></el-input>
			</el-form-item>

			<!--这里是富文本框组件-->
			<el-form-item label="内容">
				<VueEditor style="line-height:normal" v-model="form.content" :useCustomImageHandler="true" @image-added="handleImageAdded"></VueEditor>
			</el-form-item>

			<el-form-item label="栏目">
				<el-checkbox-group v-model="form.categories">
					<el-checkbox :label="item.id" v-for="(item,index) in categorylist" :key="index">{{item.name}}</el-checkbox>
				</el-checkbox-group>
			</el-form-item>
			<el-form-item label="封面">
				<el-upload :file-list="form.cover" :action="$axios.defaults.baseURL+'/upload'" :headers="{Authorization:token}" list-type="picture-card" :on-success="handleSuccess" :on-remove="handleRemove">
					<i class="el-icon-plus"></i>
				</el-upload>
			</el-form-item>
			<el-form-item label="类型">
				<el-radio-group v-model="form.type">
					<el-radio :label="1">文章</el-radio>
					<el-radio :label="2">视频</el-radio>
				</el-radio-group>
			</el-form-item>

			<el-form-item>
				<el-button type="primary" @click="onSubmit">提交</el-button>
				<el-button>取消</el-button>
			</el-form-item>
		</el-form>
	</div>
</template>

<script>
	import { VueEditor } from "vue2-editor";
	export default {
		components: {
			VueEditor
		},
		data() {
			return {
				form: {
					title: "",
					content: "",
					categories: [],
					cover: [],
					type: 1
				},
				token: localStorage.getItem("token"),
				categorylist: [],
				postId:this.$route.query.id
			}
		},
		mounted() {
			this.getCategories();
			//获取对应id的文章
			this.getPosts();
		},
		methods: {
			getPosts() {
				//如果存在文章id
				if(this.postId) {
					this.$axios({
						url: "/post/" + this.postId,
						method:"get"
					}).then(res=>{
						console.log('获取对应id的数据',res);
					    const {data}=res.data;
						
//						1,先处理category,将{id:1}的形式改成数组形式[1],方便栏目的渲染
                     let newCategories=[];
                     data.categories.forEach((element)=>{
                     	newCategories.push(element.id);
                     })
                     data.categories=newCategories;
//					2,处理图片上传组件显示的问题
                    data.cover.forEach((element,index)=>{
//                  	这里有个前提,如果是相对路径,没有加上http的url将加上基准路径才可以显示在图片上传组件中
                          if(element.url.indexOf("http")<0){
                          	element.url=this.$axios.defaults.baseURL+element.url;
                          }
//                        处理uid,这个id要是唯一的,不能相同
                       element.uid=index;
                    });
                    
//                  3,处理富文本编辑不能显示div的问题,需要替换掉div
                    data.content=data.content.replace(/div/g,'p');
//                  4,将处理过的数据data赋值到form中
                   	this.form=data;

					})
					
				}

			},
			getCategories() {
				this.$axios({
					url: "/category",
					method: "get"
				}).then(res => {
					console.log('这里是获取文章分类', res);
					const {
						data
					} = res.data;
					if(data[0].id == 0) {
						//     	  	 删除第一项我的关注
						data.shift();
					}
					if(data[0].id==999){
						//删除头条
						data.shift();
					}
					this.categorylist = data;
				})
			},
			onSubmit() {
				console.log('打印form表单数据', this.form);
				//			将form.categories改造成api需要的格式  {id:1}
				let newArr = [];
				newArr = this.form.categories.map((element) => {
					return {
						id: element
					};
				})
				//         console.log("category处理",newArr);
				this.form.categories = newArr;
				//         现在发送ajax请求发布文章
				this.$axios({
					url: this.postId?'/post_update/'+this.postId:'/post',
					method: "post",
					data: this.form
				}).then(res => {
					const {message} = res.data;
					console.log("res的值",res);
					if(message=="文章编辑成功"){
						this.$message({
                        message: '文章编辑成功',
                        type: 'success'
                       });
					}else{
						this.$message({
							message:"发布成功",
							type:"success"
						})
					}
					
//					发布文章完毕和编辑文章就跳到文章列表页
                    this.$router.push("/admin/postpage");
					
				})
			},
			handleRemove(file, fileList) {
				console.log("删除图片成功")
				console.log('filelist结果', fileList);
				//			将当前的图片列表赋值给from.cover
				this.form.cover = fileList;
			},
			handleSuccess(response, file, fileList) {
				console.log("添加图片成功")
				console.log(response)
				console.log("文件file", file)
				file.id = response.data.id;
				file.url = this.$axios.defaults.baseURL + response.data.url;
				//		    将这个file对象加到form.cover中
				this.form.cover.push(file);
			},
			handleImageAdded(file, Editor, cursorLocation, resetUploader) {
				var formdata = new FormData();
				formdata.append("file", file);
				//			发送ajax上传图片
				this.$axios({
					url: "/upload",
					method: "post",
					data: formdata
				}).then(res => {
					console.log("这里是上传图片到编辑器", res);
					const {
						data
					} = res.data;
					//         	这里需要拼接基准路径,然后才能将图片显示出来
					let url = this.$axios.defaults.baseURL + data.url;
					//下面是固定写法，将图片插入到编辑器中
					Editor.insertEmbed(cursorLocation, "image", url);
					//有一个必须要做的事情就是重置上传组件
					resetUploader();
				}).catch(err => {
					//这里是捕获错误
					console.log(err);
				})
			}

		}
	}
</script>

<style lang="less" scoped>
	.el-form {
		background-color: #fff;
		padding: 20px 20px 20px 15px;
	}
</style>